// 1. 导入 http 模块
const http = require('http')

const db = require('./db/index')

// 2. 创建 web 服务器实例
const server = http.createServer()


// 3. 启动服务器
server.listen(8848, () => {
    console.log('my server start work')
})

// 4. 为服务器实例绑定 request 事件，监听客户端的请求
server.on('request', (request, response) => {
    response.setHeader('Content-Type', 'application/json; charset=utf-8')
    response.setHeader('Access-Control-Allow-Origin', '*')
    if (request.method === 'GET' && request.url === '/api/students') {
        // response.end('nic)
        response.end(JSON.stringify(db.students()))
    } else if (request.method === 'GET' && request.url === '/api/lucystar') {
        response.end(JSON.stringify(db.lucystar()))
    } else if (request.method === 'GET' && request.url === '/api/news') {
        response.end(JSON.stringify(db.news()))
    }
    else {
        response.statusCode = 404
        response.end('404 not found')
    }
    // 设置响应的内容为JSON
    // 不能直接响应 对象/数组 需要转为字符串
})